package com.example.mydownloader.config.globalConfig

import android.text.TextUtils
import com.example.mydownloader.mymodule.log.LogUtil
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.lang.StringBuilder

/**
 * <Description> 获取配置文件的信息
 *
 * @author Wallace
 * @Date 2021/11/25 9:19
 */
object UrlConfig {

    private var filename = "url_config.txt"

    var baseUrl: String = ""
    var loginUrl: String = ""
    var preRequestUrl: String = ""
    var createPublicKeyUrl: String = ""

    fun readConfigFile(): Boolean {
        val assertManager = GlobalParameter.mContext.assets
        val inputStream: InputStream? = try {
            assertManager.open("config/$filename")
        } catch (e: Exception) {
            LogUtil.w("$e")
            null
        }
        inputStream?.apply {
            val hashMap = HashMap<String, String>()
            val lines = this.reader().readLines()
            lines.forEach {
                if (!it.startsWith("#")) {
                    val contents = it.split("=")
                    if (contents.size == 2) {
                        val key = contents[0].trim()
                        val value = contents[1].trim()
                        hashMap[key] = value
                    }
                }
            }
            LogUtil.d("$hashMap")
            if (hashMap.containsKey("baseUrl")) {
                baseUrl = hashMap["baseUrl"].toString()
            }
            if (TextUtils.isEmpty(baseUrl)) {
                throw NullPointerException("baseUrl can not be empty or null")
            }
            if (hashMap.containsKey("loginUrl")) {
                loginUrl = baseUrl + hashMap["loginUrl"].toString()
            }
            if (hashMap.containsKey("preRequestUrl")) {
                preRequestUrl = baseUrl + hashMap["preRequestUrl"].toString()
            }
            if (hashMap.containsKey("createPublicKeyUrl")) {
                createPublicKeyUrl = baseUrl + hashMap["createPublicKeyUrl"].toString()
            }
            LogUtil.d("read configuration file successfully")
            return true
        }
        LogUtil.w("can not find configuration file！")
        return false
    }
}